/**
 * 字符串中间星号
 * @returns 字符串
 */
export function stringStar(value = '默认内容', characters = '****', start = 3, end = 4) {
  const reg = new RegExp(`^(.{${start}}).*(.{${end}})$`)
  if (value)
    return value.replace(reg, `$1${characters}$2`)

  return ''
}

/**
 * @description 进行延时，以达到可以简写代码的目的 比如: await uni.$uv.sleep(20)将会阻塞20ms
 * @param {number} value 堵塞时间 单位ms 毫秒
 * @returns {Promise} 返回promise
 */
export function sleep(value = 30) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(null)
    }, value)
  })
}

/**
 * @description 对象转url参数
 * @param {object} data 对象
 * @param {boolean} isPrefix 是否自动加上"?"
 * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
 */
export function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets'): string {
  const prefix = isPrefix ? '?' : ''
  const _result = []
  if (!['indices', 'brackets', 'repeat', 'comma'].includes(arrayFormat))
    arrayFormat = 'brackets'
  for (const key in data) {
    const value = data[key]
    // 去掉为空的参数
    if (['', undefined, null].includes(value))
      continue

    // 如果值为数组，另行处理
    if (value.constructor === Array) {
      let commaStr = ''
      // e.g. {ids: [1, 2, 3]}
      switch (arrayFormat) {
        case 'indices':
          // 结果: ids[0]=1&ids[1]=2&ids[2]=3
          for (let i = 0; i < value.length; i++)
            _result.push(`${key}[${i}]=${value[i]}`)

          break
        case 'brackets':
          // 结果: ids[]=1&ids[]=2&ids[]=3
          value.forEach((_value) => {
            _result.push(`${key}[]=${_value}`)
          })
          break
        case 'repeat':
          // 结果: ids=1&ids=2&ids=3
          value.forEach((_value) => {
            _result.push(`${key}=${_value}`)
          })
          break
        case 'comma':
          // 结果: ids=1,2,3
          value.forEach((_value) => {
            commaStr += (commaStr ? ',' : '') + _value
          })
          _result.push(`${key}=${commaStr}`)
          break
        default:
          value.forEach((_value) => {
            _result.push(`${key}[]=${_value}`)
          })
      }
    }
    else {
      _result.push(`${key}=${value}`)
    }
  }
  return _result.length ? prefix + _result.join('&') : ''
}

/**
 * URL 参数转对象
 * @param url 字符串
 * @returns
 */
export function parseQueryString(url) {
  url = url || window.location.search
  const search = url[0] === '?' ? url : url.substring(url.lastIndexOf('?'))
  const q = {}
  search.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (q[k] = decodeURIComponent(v)))
  return q
}

/**
 * 格式化文件大小
 * @param filesize 文件大小
 * @param Bytes bytes单位
 * @param decimalPoint 小数点
 * @returns number
 */
export function formatFileSize(filesize: number, Bytes = 1024, decimalPoint = 2) {
  const format = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  if (filesize === 0)
    return `0${format[0]}`
  const i = Math.floor(Math.log(filesize) / Math.log(Bytes))
  return Number.parseFloat((filesize / Bytes ** i).toFixed(decimalPoint)) + format[i]
}
/**
 * 格式化时间
 * @param date 时间戳
 * @param language 语言
 */
export function timeAgo(date, language = 'cn') {
  const now = new Date().getTime();
  const diff = now - date;
  const second = 1000;
  const minute = second * 60;
  const hour = minute * 60;
  const day = hour * 24;
  const month = day * 30; // 这里简化处理，实际每个月的天数不同
  const year = day * 365; // 同样，这里简化处理，不考虑闰年

  let result;
  if (diff < second) {
      result = language === 'en' ? 'Just now' : '刚刚';
  } else if (diff < minute) {
      result = Math.floor(diff / second) + (language === 'en' ? ' seconds ago' : '秒前');
  } else if (diff < hour) {
      result = Math.floor(diff / minute) + (language === 'en' ? ' minutes ago' : '分钟前');
  } else if (diff < day) {
      result = Math.floor(diff / hour) + (language === 'en' ? ' hours ago' : '小时前');
  } else if (diff < month) {
      result = Math.floor(diff / day) + (language === 'en' ? ' days ago' : '天前');
  } else if (diff < year) {
      result = Math.floor(diff / month) + (language === 'en' ? ' months ago' : '月前');
  } else {
      result = Math.floor(diff / year) + (language === 'en' ? ' years ago' : '年前');
  }

  return result;
}